import { reqLogin, reqGetUserInfo } from '@/api/user'
import { setToken, removeToken, getToken, setUserInfo, getUserInfo, removeUserInfo } from '@/utils/storage'
import { defineStore } from 'pinia'
import { LoginForm, UserInfo } from '@/types/user'
const useUserStore = defineStore('user', {
    state() {
        return {
            tokenInfo: getToken() || {},
            userInfo: getUserInfo() || <UserInfo>{},
        }
    },
    actions: {
        setTokenFn(tokens: {
            token: string,
            refresh_token: string
        }) {
            setToken(tokens)
            this.tokenInfo = tokens
            console.log('存', tokens)
        },
        clearToken() {
            removeToken()
            removeUserInfo()
            this.tokenInfo = {
                token: '',
                refresh_token: ''
            }
        },
        async login(formList: LoginForm) {
            console.log(formList)
            const { data } = await reqLogin(formList)
            console.log(data)
            if (data.message === 'OK') {
                console.log('11111');
                this.setTokenFn(data.data)
            }
            const res = await reqGetUserInfo()
            this.userInfo = res.data.data
            setUserInfo(this.userInfo)
            console.log(123);
            // this.downloadImg(this.userInfo.photo)
        },
        async resetUserInfo() {
            const res = await reqGetUserInfo()
            this.userInfo = res.data.data
            setUserInfo(this.userInfo)
        },
        downloadImg(src: string) {
            var url = src;                            // 获取图片地址
            var a = document.createElement('a');          // 创建一个a节点插入的document
            var event = new MouseEvent('click')           // 模拟鼠标click点击事件
            a.download = '图片名字'                  // 设置a节点的download属性值
            a.href = url;                                 // 将图片的src赋值给a节点的href
            a.dispatchEvent(event)                        // 触发鼠标点击事件
            console.log('success');
        },
    }
})
export default useUserStore
